#include <string.h>
#include <stdlib.h>
#include "html.h"
static char* html_predefined_entities[]={
    "amp","&",
    "quot","\"",
    "apos","'",
    "lt","<",
    "gt",">",
    "nbsp"," ",
    //"",""
    //"",""
    //"",""
};

int html_found_predefined_entity(const char *p) {
    int counts=sizeof(html_predefined_entities)/2/sizeof(char *);
    int i,n;
    char *entity;
    int entity_len;
    int predefined_entity_index=-1;
    for (i=0;i<counts;++i) {
        entity=html_predefined_entities[i*2];
        entity_len=strlen(entity); 
        if ((strlen(p)-2)<entity_len) {
            continue;
        }
        if (p[entity_len+1]!=';') {
            continue;
        }
        predefined_entity_index=i*2;
        for (n=0;n<entity_len;++n) {
            if (p[n+1]!=entity[n]) {
                predefined_entity_index=-1;
                break;
            }
        }
        if (predefined_entity_index>=0) {
            break;
        }
    }
    return predefined_entity_index;
}

char *html_entity_decode(const char *encoded_str) {
    //uint8_t state;
    int index;
    int output_str_len=sizeof(char)*(strlen(encoded_str)+1);
    char *output_str=malloc(output_str_len);
    bzero(output_str, output_str_len);
    char *output_str_p=output_str;
    while (*encoded_str) {
        if (*encoded_str=='&') {
            if ((index=html_found_predefined_entity(encoded_str))>=0) {
                memcpy(output_str_p, html_predefined_entities[index+1], strlen(html_predefined_entities[index+1]));
                output_str_p+=strlen(html_predefined_entities[index+1]);
                encoded_str+=strlen(html_predefined_entities[index])+2;
                continue;
            }
        }
        *output_str_p=*encoded_str;
        ++output_str_p;
        ++encoded_str;
    }
    return output_str;
}
